package com.xmlt.ui.server;

import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import com.xmlt.core.template.TemplateManager;
import com.xmlt.ui.builder.BuilderPlugin;
import com.xmlt.ui.editors.browsereditor.BrowserEditor;

public class EditorContext {
	public static final String PROJECT_NAME_PARAM = "project";
	public static final String PATH_PARAM = "path";
	public static final String EDITOR_CONTEXT_ID_PARAM = "contextId";
	
	private IFile editedFile;
	private BrowserEditor editor;
	private String contextId;
	private Object wrappedObject;
	public EditorContext(IFile file, BrowserEditor ed, String id) {
		editedFile = file;
		editor = ed;
		contextId = id;
	}
	
	public Object getWrappedObject() {
		return wrappedObject;
	}

	public void setWrappedObject(Object wrappedObject) {
		this.wrappedObject = wrappedObject;
	}

	public String getDocumentString() {
		Document doc = editor.getEditedDocument();
		doc.getDocumentElement().setAttribute(EDITOR_CONTEXT_ID_PARAM, contextId);
		String docString = printNode(doc.getDocumentElement());
		return docString;
	}
	
	public String getContextId() {
		return contextId;
	}
	
	public TemplateManager getTemplateManager() {
		IProject project = editedFile.getProject();
		return BuilderPlugin.getTemplateManager(project);
	}
	
	private String printNode(Node n) {
		try {
			Transformer xformer = TransformerFactory.newInstance()
					.newTransformer();
			xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
			StringWriter sw = new StringWriter();
			xformer.transform(new DOMSource(n), new StreamResult(sw));
			return sw.toString();
		} catch (TransformerConfigurationException e) {
			//e.printStackTrace();
		} catch (TransformerException e) {
			//e.printStackTrace();
		}
		return "";
	}

}
